package com.example.yls.demoa;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity
 implements IOnDataChangeListener{
    private ListView lvStudent;
    private Button btnAdd;
    private EditText et_key;
    private Button btnSearch;
    private List<Student> studentArrayList = new ArrayList<>();
    private StuentAdapter adapter;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_key = findViewById(R.id.key_word);
        lvStudent = findViewById(R.id.lv_stu);
        btnAdd = findViewById(R.id.btn_add);
        btnSearch = findViewById(R.id.btn_search);

        db = DBManger.getIntance(this).getWritableDatabase();

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddActivity.class);
                startActivityForResult(intent, 1001);
            }
        });

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String keyWord = et_key.getText().toString();
                if("".equals(keyWord)){
                    reload();
                    return;
                }

                studentArrayList = search(keyWord);
                adapter.changeData(studentArrayList);
            }
        });

        //长按删除效果
        lvStudent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
                //显示删除按钮
                view.findViewById(R.id.line_view).setVisibility(View.INVISIBLE);
                view.findViewById(R.id.item_del).setVisibility(View.VISIBLE);
                //定时超时未操作隐藏删除按钮
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = 0;
                        Bundle bundle = new Bundle();
                        bundle.putInt("id",i);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }, 2000);

                return false;
            }
        });

        //点击跳转编辑页面
        lvStudent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Student student = studentArrayList.get(i);
                Intent intent = new Intent();

                intent.putExtra("stuno",student.getStuno());
                intent.putExtra("name",student.getName());
                intent.putExtra("age",student.getAge());

                intent.setClass(MainActivity.this, EditActivity.class);
                startActivityForResult(intent, 1002);
            }
        });

        // 读取数据
        studentArrayList = readDataFromDB();

        adapter = new StuentAdapter(MainActivity.this, MainActivity.this,
                studentArrayList);
        lvStudent.setAdapter(adapter);


    }

    /**
     * 更新UI
     */
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
//            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    View view = lvStudent.getChildAt(msg.getData().getInt("id"));
                    if(view!=null){
                        view.findViewById(R.id.item_del).setVisibility(View.INVISIBLE);
                        view.findViewById(R.id.line_view).setVisibility(View.VISIBLE);
                    }
                    break;
            }

        }
    };

    /**
     * 模糊查询姓名、学号，年龄为精确查询
     * @param keyWord
     * @return
     */
    private List<Student> search(String keyWord){
        String where = "stuno like ? or name like ? or age=?";

        List<Student> list = new ArrayList<>();
        Log.e("KingSir",where);
        Cursor cursor = db.query("student", null, where,
                new String[]{"%"+keyWord+"%","%"+keyWord+"%",keyWord},
                null,null,null);
        Log.e("KingSir","count:"+cursor.getCount());
        if(cursor == null || cursor.getCount() == 0){
            return list;
        }

        for(cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()){
            String stuno = cursor.getString(0);
            String stuname = cursor.getString(1);
            int stuAge = cursor.getInt(2);
            list.add(new Student(stuno, stuname, stuAge));
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == 2001){
            String no = data.getStringExtra("NO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);
            Student student = new Student(no, name, age);

            addToStudentDB(student);
        }else if(resultCode == 2002){
            String odlNo = data.getStringExtra("ODL_NO");
            String no = data.getStringExtra("NO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);
            Student student = new Student(no, name, age);

            updateStudentDB(odlNo, student);
        }

    }

    /**
     * 更新学生信息
     * @param odlNo
     * @param student
     */
    private void updateStudentDB(String odlNo, Student student) {
        ContentValues values = new ContentValues();
        values.put("stuno", student.getStuno());
        values.put("name", student.getName());
        values.put("age", student.getAge());
        String sql = "stuno=?";
        db.update("student",values,sql,new String[]{odlNo});

        reload();
    }

    /**
     * 添加到数据库
     * @param student
     */
    private void addToStudentDB(Student student) {
        ContentValues values = new ContentValues();
        values.put("stuno", student.getStuno());
        values.put("name", student.getName());
        values.put("age", student.getAge());
        db.insert("student", null, values);

        reload();
    }

    /**
     * 重新加载列表
     */
    private void reload(){
        studentArrayList = readDataFromDB();
        adapter.changeData(studentArrayList);
    }

    /**
     * 读取数据库数据
     * @return
     */
    private ArrayList<Student> readDataFromDB() {
        ArrayList<Student>  studentArrayList = new ArrayList<>();

        Cursor cursor = db.query("student", null,null,null,null,null,null);

        if(cursor == null || cursor.getCount() == 0){
            return studentArrayList;
        }

        for(cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()){
            String stuno = cursor.getString(0);
            String stuname = cursor.getString(1);
            int stuAge = cursor.getInt(2);
            studentArrayList.add(new Student(stuno, stuname, stuAge));
        }

        return studentArrayList;
    }

    @Override
    public void addStudent() {

    }

    @Override
    public void delStudent(String stuno) {
        String sql = "stuno=?";
        db.delete("student",sql,new String[]{stuno});
        reload();
    }
}
